import React, {Component, createRef} from 'react'
import {
  Button,
  Form,
  Radio,
  Select,
  DatePicker,
  Alert,
  Table,
  Image, Tag, Space, Modal, message,
} from "antd";
import {
  EditOutlined,
  DeleteOutlined,
  WechatOutlined
} from '@ant-design/icons'
import {delArticle, getArticleList, getChannels} from "api/article";
import defaultImg from 'assets/logo.png'
import CommonBread from "../components/CommonBread";

const {Item} = Form
const {Group} = Radio
const {Option} = Select
const {RangePicker} = DatePicker

const articleStatus = {
  0: {text: '草稿', color: 'gold'},
  1: {text: '待审核', color: 'lime'},
  2: {text: '审核通过', color: 'green'},
  3: {text: '审核失败', color: 'red'},
}

// 作用：判断是否最后一条数据
// total: 总数据
// pageSize: 每一页的条数
// currentPage: 当前页码数
// return true是最后一条数据
function isEndData(total, pageSize, currentPage) {
  return (total - 1) % pageSize === 0 // 判断总数减一 / 页码是否整除？如果整除 ==> 表示正好是当前页面最后一条
    && (total - 1) / pageSize < currentPage // 如果减一的页码数小于当前页码数 ==> 表示处于最后一页
    && currentPage !== 1; // 并且不是第一页
}


export default class ArticleList extends Component {
  formRef = createRef()
  state = {
    channels: [],
    total_count: 0, // 总数量
    page: 1, // 当前页码数
    per_page: 10, // 每页多少条数据
    articleList: [], // 文章列表数据
    tableLoading: false
  }

  componentDidMount() {
    this.getChannelList()
    this.getArticleList()
  }

  getChannelList = async () => {
    const res = await getChannels()
    this.setState({
      channels: res.data.channels
    })
  }

  handleSubmit = async (values) => {
    // 拿到的参数进行二次处理
    const params = {}

    // 处理status
    params.status = values.status === -1 ? null : values.status

    // 频道id
    params.channel_id = values.channel_id || null

    // 日期
    if (values.pubDate) {
      params.begin_pubdate = values.pubDate[0].format('YYYY-MM-DD') // [Moment, Moment] 2022-03-05
      params.end_pubdate = values.pubDate[1].format('YYYY-MM-DD')
    }

    console.log(params)

    //   接口请求 获取文章列表数据
    this.getArticleList(params)
  }

  getArticleList = async (params = {}) => {
    const tempParams = {
      page: this.state.page,
      per_page: this.state.per_page,
      ...params
    }
    if (isEndData(this.state.total_count, tempParams.per_page, tempParams.page)) {
      //  页码-1
      tempParams.page--
    }
    this.setState({
      tableLoading: true
    })
    //
    // 怎么用这个方法
    try {
      const res = await getArticleList(tempParams)
      this.setState({
        articleList: res.data.results,
        total_count: res.data.total_count,
        page: res.data.page,
        per_page: res.data.per_page,
        tableLoading: false
      })
    } catch (e) {
      this.setState({
        tableLoading: false
      })
    }
  }

  pageChange = (page, pageSize) => {
    this.getArticleList({
      page: page,
      per_page: pageSize
    })
  }

  handleDelete = id => () => {
    //弹出框提示
    Modal.confirm({
      title: '提示',
      content: "是否确认删除？",
      icon: <WechatOutlined/>,
      onOk: async () => {
        //  删除数据
        await delArticle(id)
        message.success('删除成功')
        this.formRef.current.submit()
      }
    })
  }

  render() {
    const columns = [
      {
        title: '封面',
        render(data) {
          const {type, images} = data.cover
          if (type === 0) {
            return <Image src={defaultImg} width={100}/>
          }
          return <Image width={100} src={images[0]} fallback={defaultImg}/>
        }
      },
      {
        title: '标题',
        dataIndex: 'title',
      },
      {
        title: '状态',
        dataIndex: 'status',
        render(data) {
          const {color, text} = articleStatus[data]
          return <Tag color={color}>{text}</Tag>
        }
      },
      {
        title: '发布时间',
        dataIndex: 'pubdate',
      },
      {
        title: '阅读数',
        dataIndex: 'read_count',
      },
      {
        title: '评论数',
        dataIndex: 'comment_count',
      },
      {
        title: '点赞数',
        dataIndex: 'like_count',
      },
      {
        title: '操作',
        render: (data) => {
          return <Space>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined/>}
              onClick={() => this.props.history.push('/home/publish?id=' + data.id)}
            />
            <Button
              danger
              type="primary"
              shape="circle"
              icon={<DeleteOutlined/>}
              onClick={this.handleDelete(data.id)}
            />
          </Space>
        }
      },
    ]
    return <div className="home">
      <CommonBread title={'文章列表'}/>
      <Form
        initialValues={{
          status: -1
        }}
        onFinish={this.handleSubmit}
        ref={this.formRef}
      >
        <Item label={'状态'} name={'status'}>
          <Group>
            <Radio value={-1}>全部</Radio>
            <Radio value={0}>草稿</Radio>
            <Radio value={1}>待审核</Radio>
            <Radio value={2}>审核通过</Radio>
            <Radio value={3}>审核失败</Radio>
          </Group>
        </Item>
        <Item label={'频道'} name={'channel_id'}>
          <Select
            style={{
              width: 200
            }}
            allowClear
            name={'channel_id'}
            placeholder={'请选择频道'}
            size={'middle'}
          >
            {
              this.state.channels.map(item => (
                <Option value={item.id} key={item.id}>{item.name}</Option>
              ))
            }
          </Select>
        </Item>
        <Item
          label={'日期'}
          name={'pubDate'}
        >
          <RangePicker/>
        </Item>
        <Item>
          <Button
            htmlType={'submit'}
            type={'primary'}
          >筛选</Button>
        </Item>
      </Form>

      {/*   总数量做一个展示*/}
      <Alert message={`根据筛选条件共查询到 ${this.state.total_count} 条结果:`} type="info"/>
      <Table
        loading={this.state.tableLoading}
        rowKey="id"
        columns={columns}
        dataSource={this.state.articleList}
        pagination={{
          position: ['bottomCenter'],
          current: this.state.page,
          pageSize: this.state.per_page,
          total: this.state.total_count,
          onChange: this.pageChange,
          pageSizeOptions: [2, 4, 6, 10, 50, 100]
        }}
      />
    </div>
  }
}
